/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package strategies;

import common.EntityPresentation;
import common.ParamStorage;
import dao.EntityDAO;
import database.DatabaseException;
import html.XHtmlFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import localization.Localization;

/**
 *
 * @author Alejandro
 */
public class DeleteEntityStrategy implements Strategy {

    @Override
    public void execute(WebContext ctx) {
        XHtmlFormatter provider = ctx.getWebFormatter();
        provider.startDiv("", "operationResult");
        //provider.writeP("center", this.getClass().getName());
        List<String> keys = new LinkedList<String>();
        ParamStorage storage = ctx.getParamStorage();
        Map<String, String> rows = storage.getRows();
        EntityDAO dao = new EntityDAO(ctx.getUid());
        boolean emptySelection = true;
        for (String key : rows.keySet()) {
            if (rows.get(key).equals("on")) {
                try {
                    EntityPresentation ep;
                    ep = dao.findByPrimaryKey(key);
                    if (ep != null) {
                        if (emptySelection)
                            emptySelection = false;
                        dao.delete(ep);
                        provider.putSuccess(String.format(Localization.getString("DeleteSuccess"), key));
                    }
                } catch (DatabaseException ex) {
                    provider.putError(String.format(Localization.getString("FailedDelete"), key, ex.getMessage()));
                }
            }
        }
        if (emptySelection) {
            provider.putError(Localization.getString("NoRowSelected"));
        }
        provider.endDiv();
    }
}
